package com.lwj.diao.Utils;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class UtilClassLoaderExpand extends ClassLoader {
    private String location;

    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] datas = this.loadClassData(name);
        String substring = name.substring(0, name.lastIndexOf(".") + 1);
        return this.defineClass(name, datas, 0, datas.length);
    }

    public String getLocation() {
        return this.location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected byte[] loadClassData(String name) {
        FileInputStream resourceAsStream = null;
        if (this.location.indexOf("/bin/") > -1) {
            this.location = this.location.substring(0, this.location.length() - 4);
        }
        String classPath = this.location + name.replace(".", "/") + ".class";
        byte[] datas = null;
        try {
            int b;
            resourceAsStream = new FileInputStream(classPath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((b = resourceAsStream.read()) != -1) {
                bos.write(b);
            }
            datas = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resourceAsStream != null) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return datas;
    }
}
